from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.models.message_model import Message
from app.models.data_model import Summary, DataUpload
from app.services.model_service import model_service  # 导入模型服务
from app import db
import uuid

chat_bp = Blueprint('chat', __name__)

@chat_bp.route('/messages', methods=['GET'])
@jwt_required()
def get_messages():
    current_user_id = int(get_jwt_identity())
    conversation_id = request.args.get('conversation_id')
    
    query = Message.query.filter_by(user_id=current_user_id)
    if conversation_id:
        query = query.filter_by(conversation_id=conversation_id)
    
    messages = query.order_by(Message.created_at.asc()).all()
    return jsonify([message.to_dict() for message in messages]), 200

@chat_bp.route('/messages', methods=['POST'])
@jwt_required()
def create_message():
    current_user_id = int(get_jwt_identity())
    data = request.get_json()
    
    # 如果没有提供conversation_id，创建一个新的
    conversation_id = data.get('conversation_id', str(uuid.uuid4()))
    
    # 获取用户输入的内容和选择的模型
    user_content = data['content']
    model = data.get('model', 'model_1')  # 默认使用model_1
    
    # 保存用户消息
    user_message = Message(
        user_id=current_user_id,
        content=user_content,
        is_user=True,
        conversation_id=conversation_id
    )
    db.session.add(user_message)
    
    # 使用模型服务生成摘要和关键词
    summary_text, keywords, coreference_id, coreference_text = model_service.generate_summary_and_keywords(
        dialogue=user_content,  # 直接使用用户输入作为对话内容
        model_name=model
    )
    
    # 使用生成的摘要作为AI回复
    ai_response = summary_text
    
    # 保存AI回复消息
    ai_message = Message(
        user_id=current_user_id,
        content=ai_response,
        is_user=False,
        conversation_id=conversation_id
    )
    db.session.add(ai_message)
    
    # 创建一个虚拟的DataUpload记录，用于关联聊天生成的摘要
    # 首先检查是否已经有专门用于聊天摘要的虚拟Upload记录
    chat_upload = DataUpload.query.filter_by(
        user_id=current_user_id,
        original_file_name='chat_summaries'
    ).first()
    
    if not chat_upload:
        # 如果没有，创建一个新的
        chat_upload = DataUpload(
            user_id=current_user_id,
            file_name='chat_summaries.json',
            original_file_name='chat_summaries',
            file_size=0,
            file_type='json',
            status='completed'
        )
        db.session.add(chat_upload)
        db.session.flush()  # 获取ID但不提交
    
    # 将对话-摘要对存储到Summary表
    summary = Summary(
        upload_id=chat_upload.id,
        fname=f"chat_{conversation_id}",
        dialogue=user_content,  # 用户问题作为对话
        summary=summary_text,   # 模型生成的摘要
        keywords=keywords,  # 添加关键词标签
        coreference_id=coreference_id,
        coreference_text=coreference_text
    )
    db.session.add(summary)
    
    db.session.commit()
    
    return jsonify({
        'conversation_id': conversation_id,
        'messages': [user_message.to_dict(), ai_message.to_dict()]
    }), 201

@chat_bp.route('/conversations', methods=['GET'])
@jwt_required()
def get_conversations():
    current_user_id = int(get_jwt_identity())
    
    # 获取用户的所有对话ID及最后消息时间
    conversations = db.session.query(
        Message.conversation_id,
        db.func.max(Message.created_at).label('last_message_time')
    ).filter_by(
        user_id=current_user_id
    ).group_by(
        Message.conversation_id
    ).order_by(
        db.desc('last_message_time')
    ).all()
    
    # 获取每个对话的最后一条消息内容
    result = []
    for conv in conversations:
        # 获取该对话的第一条用户消息作为标题
        first_user_message = Message.query.filter_by(
            user_id=current_user_id,
            conversation_id=conv.conversation_id,
            is_user=True
        ).order_by(Message.created_at.asc()).first()
        
        result.append({
            'conversation_id': conv.conversation_id,
            'last_message_time': conv.last_message_time.isoformat(),
            'last_message_content': first_user_message.content if first_user_message else None
        })
    
    return jsonify(result), 200

@chat_bp.route('/conversations/<conversation_id>', methods=['DELETE'])
@jwt_required()
def delete_conversation(conversation_id):
    current_user_id = int(get_jwt_identity())
    
    # 查找属于当前用户的所有该对话的消息
    messages = Message.query.filter_by(
        user_id=current_user_id,
        conversation_id=conversation_id
    ).all()
    
    # 如果没有找到任何消息，返回404
    if not messages:
        return jsonify({'error': '对话不存在'}), 404
    
    # 删除所有该对话的消息
    for message in messages:
        db.session.delete(message)
    
    db.session.commit()
    
    return jsonify({'message': '对话已删除'}), 200 